package com.hxzy.controller;


import com.hxzy.common.RabbitMQConst;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.concurrent.ListenableFutureCallback;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

@Log4j2
@RestController
public class DirectExchangeController {
    /**
     * rabbit封装好的消息发送的模板类
     */
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * spring:
     *   rabbitmq:
     *       publisher-confirm-type: correlated
     * @param key
     * @return
     */
    @GetMapping(value = "/direct/send")
    public String  sendMsg(String key){
        String msgId="ORDER-"+ UUID.randomUUID().toString();
        CorrelationData  correlationData=new CorrelationData(msgId);
        //设定消息的异步回调接口
        correlationData.getFuture().addCallback(new ListenableFutureCallback<CorrelationData.Confirm>() {

            @Override
            public void onFailure(Throwable ex) {
                log.error(ex);
                //你想办法如何来处理
            }

            //消息投递成功
            @Override
            public void onSuccess(CorrelationData.Confirm result) {
                 if(result.isAck()){
                    log.info("写入消息id到redis中:"+msgId);
                 }else{
                     //消息被投递失败  拒绝了 (id重复的，队列满了)
                    log.error("写入消息id到redis-error中:"+msgId);
                 }
            }
        });

        //发送消息
        this.rabbitTemplate.convertAndSend(RabbitMQConst.SHOP_DIRECT_EXCHANGE,key, "direct"+Math.random(),correlationData);


        return "direct-exchange发送消息成功";
    }
}
